package com.jiezuo.auth.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.collection.CollectionUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jiezuo.auth.entity.*;
import com.jiezuo.auth.mapper.DepartMapper;
import com.jiezuo.auth.mapper.UserMapper;
import com.jiezuo.auth.service.*;
import com.jiezuo.common.constant.SysConstant;
import com.jiezuo.common.enums.ResultEnums;
import com.jiezuo.common.exception.BusinessRuntimeException;
import com.jiezuo.common.util.*;
import com.jiezuo.common.vo.PageVo;
import com.jiezuo.common.vo.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.*;
import java.util.stream.Collectors;

@Slf4j
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

    @Autowired
    UserMapper mapper;
    @Autowired
    private DepartMapper departMapper;
    @Autowired
    private DepartService departService;
    @Autowired
    private UserRoleService userRoleService;
    @Autowired
    private DepartUserService departUserService;
    @Autowired
    private StringRedisTemplate redisTemplate;
    //本地存放路径资源路径
    @Value("${template.file-save-path}")
    public String templateFileSavePath;

    @Value("${file.file-read-path}")
    private String fileReadPath;

//    @Autowired
//    private SysClient sysClient;
//
//    @Autowired
//    private WSClient wsClient;

//    @Resource
//    private PositionService positionService;

    @Override
    public IPage<User> findPage(Page page, User user) {
        page.setRecords(mapper.findList(page, user));
        return page;
    }

    @Override
    public List<User> findList(User user) {
        return mapper.findList(user);
    }

    @Override
    public List<User> findDepartDownList(User user) {
        List<Depart> list = departService.list();
        String ids = "";
        //所有子级ID
        String allChildrenIds = allChildren(list, ids, user.getDepart_id());
        String[] arr = allChildrenIds.split(",");
        List<String> dept_ids = Arrays.asList(arr);
        User user1 = new User();
        user1.setDept_ids(dept_ids);
        List<User> userList = this.findList(user1);
        for (User u : userList) {
            //拼接头像
            u.setAvatar(fileReadPath + u.getAvatar());
            //通过用户查询部门
            List<Depart> departs = this.getDepartsByUserId(u.getId());
            u.setDepts(departs);
            //通过用户查询角色
            List<Role> roles = this.getRolesByUserId(u.getId());
            u.setRoles(roles);
        }
        return userList;
    }

    @Override
    public List<Depart> getDepartsByUserId(String user_id) {
        return mapper.getDepartsByUserId(user_id);
    }

    @Override
    public List<Role> getRolesByUserId(String user_id) {
        return mapper.getRolesByUserId(user_id);
    }

    @Override
    public List<User> findBusinessList() {
        return mapper.findBusinessList();
    }

    @Override
    public Result<IPage<User>> findUserList(PageVo pageVo, User user) {
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        if (user.getIdList() != null && user.getIdList().size() > 0) {
            queryWrapper.in("id", user.getIdList());
        }
        queryWrapper.eq("is_delete", "0");
        IPage<User> page = this.page(PageUtil.initMpPage(pageVo), queryWrapper);
        return new ResultUtil<IPage<User>>().setData(page);
    }

    @Override
    public List<User> findUserByDeparts(User user) {
        List<User> list = new ArrayList<>();
        //通过传的数据
        if (user.getDepart_ids() != null && user.getDepart_ids().size() > 0) {
            for (Depart depart : user.getDepart_ids()) {
                user.setDepart_id(depart.getId());
                List<User> userList = mapper.findList(user);
                for (User user1 : userList) {
                    list.add(user1);
                }
            }
        }
        return list;
    }

    @Override
    public List<Map<String, Object>> findSignList() {
        return mapper.findSignList();
    }

    @Override
    public void saveUser(User user) {
        VerifyUtil.notEmpty("编码", user.getUser_code());
        VerifyUtil.notEmpty("用户名", user.getUser_name());
//        if (!StringUtil.isNotEmpty(user.getUser_code())) {//编号为空，后台自动生成
//            QueryWrapper<User> queryWrapper = new QueryWrapper<>();
//            queryWrapper.select("user_code", "user_name");
//            List<User> list = this.list(queryWrapper);
//            int count = list.size();
//            String user_code = getNumberByField(list, count);
//            user.setUser_code(user_code);
//        }
//        if (!StringUtil.isNotEmpty(user.getUser_name())) {//用户名为空，后台自动生成
//            QueryWrapper<User> queryWrapper = new QueryWrapper<>();
//            queryWrapper.select("user_code", "user_name");
//            List<User> list = this.list(queryWrapper);
//            int count = list.size();
//            String user_name = getNumberByField(list, count);
//            user.setUser_name(user_name);
//        }
        //非空校验
        // VerifyUtil.notEmpty("user_name",user.getUser_name());
        VerifyUtil.notEmpty("密码", user.getPassword());
        //判断用户名是否已存在
        QueryWrapper<User> queryWrapper1 = new QueryWrapper<>();
        queryWrapper1.eq("user_name", user.getUser_name());
        List<User> list1 = this.list(queryWrapper1);
        if (list1.size() > 0) {
            //用户名已存在
            throw new BusinessRuntimeException(ResultEnums.USER_NAME_ALREADY_EXISTS.getReasonPhraseCN());
        }
        //判断用户编号是否已存在
        QueryWrapper<User> queryWrapper2 = new QueryWrapper<>();
        queryWrapper2.eq("user_code", user.getUser_code());
        List<User> list2 = this.list(queryWrapper2);
        if (list2.size() > 0) {
            //用户编号已存在
            throw new BusinessRuntimeException(ResultEnums.USER_CODE_ALREADY_EXISTS.getReasonPhraseCN());
        }
        //判断用户真实姓名是否已存在
        QueryWrapper<User> queryWrapper3 = new QueryWrapper<>();
        queryWrapper3.eq("real_name", user.getReal_name());
        List<User> list3 = this.list(queryWrapper3);
        if (list3.size() > 0) {
            //用户姓名已存在
            throw new BusinessRuntimeException(ResultEnums.REAL_NAME_ALREADY_EXISTS.getReasonPhraseCN());
        }
        //用户盐
        String satl = StringUtil.randomString(10);
        user.setSalt(satl);
        //密码加密
        user.setPassword(MD5Util.MD5(user.getPassword() + satl));

        //当头像为空时，添加默认用户头像
        if (!StringUtil.isNotEmpty(user.getAvatar())) {
            if ("0".equals(user.getSex())) { //男
                user.setAvatar("default/nan.jpg");
            } else { //女
                user.setAvatar("default/nv.jpg");
            }
        }
        // 签名问题处理
        if (StringUtil.isNotEmpty(user.getSigned_photos())) {
            String path = base64ToImage(user.getReal_name(), user.getSigned_photos());
            user.setSigned_path(path);
        } else {
            user.setSigned_path("");
        }

        this.save(user);
        //保存角色
        List<Role> roles = user.getRoles();
        List<UserRole> urs = new ArrayList<>();
        // 主角色
//        if(StringUtil.isNotEmpty(user.getMain_role())){
//            UserRole userRole = new UserRole();
//            userRole.setRole_id(user.getMain_role());
//            userRole.setUser_id(user.getId());
//            // userRole.setLevel("0");
//            urs.add(userRole);
//        }
        if (roles != null) {
            for (int i = 0; i < roles.size(); i++) {
                UserRole userRole = new UserRole();
                userRole.setRole_id(roles.get(i).getId());
                userRole.setUser_id(user.getId());
                // userRole.setLevel(String.valueOf(i+1));
                urs.add(userRole);
            }
            userRoleService.saveBatch(urs);
        }
        //保存部门
        List<Depart> departs = user.getDepts();
        List<DepartUser> dus = new ArrayList<>();
        // 主部门
        if (StringUtil.isNotEmpty(user.getMain_dept())) {
            DepartUser departUser = new DepartUser();
            departUser.setDepart_id(user.getMain_dept());
            departUser.setUser_id(user.getId());
            dus.add(departUser);
        }
        if (departs != null) {
            for (Depart depart : departs) {
                if (!depart.getId().equals(user.getMain_dept())) {//是否主部门中已经存在,不存在，添加
                    DepartUser departUser = new DepartUser();
                    departUser.setDepart_id(depart.getId());
                    departUser.setUser_id(user.getId());
                    dus.add(departUser);
                }
            }
            departUserService.saveBatch(dus);
        }
    }

    @Override
    public void updateUser(User user) {
        VerifyUtil.notEmpty("数据序号", user.getId());
        VerifyUtil.notEmpty("编号", user.getUser_code());
        VerifyUtil.notEmpty("用户名", user.getUser_name());
//        QueryWrapper<User> queryUser = new QueryWrapper<>();
//        queryUser.eq("id", user.getId());//id不是自己
//        queryUser.eq("is_delete", "0");
//        User one = userService.getOne(queryUser);
//        if(one == null){
//            throw new BusinessRuntimeException("用户不存在");
//        }
        //判断用户名是否已存在
        QueryWrapper<User> queryWrapper1 = new QueryWrapper<>();
        queryWrapper1.ne("id", user.getId());//id不是自己
        queryWrapper1.eq("user_name", user.getUser_name());
        List<User> list = this.list(queryWrapper1);
        if (list.size() > 0) {
            //用户名已存在
            throw new BusinessRuntimeException(ResultEnums.USER_NAME_ALREADY_EXISTS.getReasonPhraseCN());
        }
        //判断用户编号是否已存在
        QueryWrapper<User> queryWrapper2 = new QueryWrapper<>();
        queryWrapper2.ne("id", user.getId());//id不是自己
        queryWrapper2.eq("user_code", user.getUser_code());
        List<User> list1 = this.list(queryWrapper2);
        if (list1.size() > 0) {
            //用户编号已存在
            throw new BusinessRuntimeException(ResultEnums.USER_CODE_ALREADY_EXISTS.getReasonPhraseCN());
        }
        //判断用户真实姓名是否已存在
        QueryWrapper<User> queryWrapper3 = new QueryWrapper<>();
        queryWrapper3.ne("id", user.getId());//id不是自己
        queryWrapper3.eq("real_name", user.getReal_name());
        List<User> list3 = this.list(queryWrapper3);
        if (list3.size() > 0) {
            //用户姓名已存在
            throw new BusinessRuntimeException(ResultEnums.REAL_NAME_ALREADY_EXISTS.getReasonPhraseCN());
        }

        //修改时，不允许修改密码
//        String satl = null;
//        String password = null;
//        if(StringUtil.isNotEmpty(user.getPassword())){
//            //用户盐
//            String satl = StringUtil.randomString(10);
//            user.setSalt(satl);
//            //密码加密
//            user.setPassword(MD5Util.MD5(user.getPassword() + satl));
//        }

        // 签名问题处理
        if (StringUtil.isNotEmpty(user.getSigned_photos())) {
            String path = base64ToImage(user.getReal_name(), user.getSigned_photos());
            user.setSigned_path(path);
        } else {
            user.setSigned_path("");
        }
        this.updateById(user);

        // 保存前清空
        QueryWrapper<UserRole> urQuery = new QueryWrapper();
        urQuery.eq("user_id", user.getId());
        userRoleService.remove(urQuery);

        //保存角色
        List<Role> roles = user.getRoles();
        List<UserRole> urs = new ArrayList<>();
        // 主角色
//        if(StringUtil.isNotEmpty(user.getMain_role())){
//            UserRole userRole = new UserRole();
//            userRole.setRole_id(user.getMain_role());
//            userRole.setUser_id(user.getId());
//            // userRole.setLevel("0");
//            urs.add(userRole);
//        }
        if (roles != null) {
            for (int i = 0; i < roles.size(); i++) {
                UserRole userRole = new UserRole();
                userRole.setRole_id(roles.get(i).getId());
                userRole.setUser_id(user.getId());
                // userRole.setLevel(String.valueOf(i+1));
                urs.add(userRole);
            }
            userRoleService.saveBatch(urs);
        }
        // 保存前清空
        QueryWrapper<DepartUser> duQuery = new QueryWrapper();
        duQuery.eq("user_id", user.getId());
        departUserService.remove(duQuery);
        //保存部门
        List<Depart> departs = user.getDepts();
        List<DepartUser> dus = new ArrayList<>();
        // 主部门
        if (StringUtil.isNotEmpty(user.getMain_dept())) {
            DepartUser departUser = new DepartUser();
            departUser.setDepart_id(user.getMain_dept());
            departUser.setUser_id(user.getId());
            dus.add(departUser);
        }
        if (departs != null) {
            for (Depart depart : departs) {
                if (!depart.getId().equals(user.getMain_dept())) {//是否主部门中已经存在,不存在，添加
                    DepartUser departUser = new DepartUser();
                    departUser.setDepart_id(depart.getId());
                    departUser.setUser_id(user.getId());
                    dus.add(departUser);
                }
            }
            departUserService.saveBatch(dus);
        }
        // 清理缓存
        Boolean delRoles = redisTemplate.delete(SysConstant.REDIS_ROLE + user.getUser_name());
        // 清理redis数据权限信息
        Set<String> keys = redisTemplate.keys(SysConstant.REDIS_DATA_AUTHORITY + user.getUser_name());
        Long delete = redisTemplate.delete(keys);
        if (delete > 0) {
            log.info("删除redis中的DATA_AUTHORITY:USER_AUTHORITY_{}成功！", user.getUser_name());
        } else {
            log.error("删除redis中的DATA_AUTHORITY:USER_AUTHORITY_{}失败！", user.getUser_name());
        }
    }

    @Override
    public Map<String, Object> getUserInfoByUserId(String id) {
        Map<String, Object> map = new HashMap<>();
        //用来返回对应所有人员
        Set<User> userInfo = null;
        Set<Depart> departInfo = null;
        String is_director = "0";//默认不是所长
        //先查出来改人员是否所长
        List<User> users = mapper.findDirectorById(id);
        if (!CollectionUtil.isEmpty(users)) {
            is_director = "1";
            //查询出所对应的检测部门 可能多个检测部门
            List<Depart> departs = null;
            for (User user : users) {
                departs = departMapper.findDepartById(user.getId());
            }
            if (!CollectionUtil.isEmpty(departs)) {
                //有可能重复 需要去重
                departInfo = new HashSet<>(departs);
                //根据部门查询对应的所有人员
                List<User> userList = null;
                for (Depart depart : departInfo) {
                    userList = mapper.findUserInfoByDepartId(depart.getId());
                }
                userInfo = new HashSet<>(userList);
            }
        }
        //不是所长，拿到对应部门所有人员
        if (CollectionUtil.isEmpty(users)) {
            //拿到对应所有的检测部门
            List<Depart> departs = departMapper.findDepartById(id);
            if (!CollectionUtil.isEmpty(departs)) {
                List<User> userList = null;
                //拿这些部门对应的所有人员信息
                departInfo = new HashSet<>(departs);
                for (Depart depart : departs) {
                    userList = mapper.findUserInfoByDepartId(depart.getId());
                }
                userInfo = new HashSet<>(userList);
            }
        }
        map.put("userInfo", userInfo);
        map.put("departInfo", departInfo);
        map.put("is_director", is_director);
        return map;
    }

    @Override
    public IPage<User> findUserInfoByUserPage(Page page, User user) {
        //用来返回对应所有人员
        //先查出来改人员是否所长
//        List<User> users = mapper.findDirectorById(user.getId());
//        if (!CollectionUtil.isEmpty(users)) {
//            page.setRecords(mapper.findUserInfoByUser(page, user));
//        }
//        //不是所长，拿到对应部门所有人员
//        if (CollectionUtil.isEmpty(users)) {
//            page.setRecords(mapper.findUserInfoByUser(page, user));
//        }
        // 需要展示第一研究院，第二研究院。。。的所有人
        // 经过讨论，解决方案： 2023年3月7日10:22:04 逻辑变更，查到上级如果存在检测部门，就查出检测部门的所有人
//        List<String> allAncestor = mapper.findAllAncestorByUserId(user.getId());
//        List<String> deptIds = new ArrayList<>();
//        for (String ancestor : allAncestor) {
//            deptIds.addAll(Arrays.asList(ancestor.split(",")));
//        }
//        if (deptIds.size() > 0) {
//            List<User> users = mapper.findUsersByDepartId(deptIds);
//            page.setRecords(users);
//        } else {
//            page.setRecords(new ArrayList());
//        }
        List<Map<String, Long>> list = mapper.isDepartByUserId(user.getId());
        Map<String, Long> map = list.get(0);
        Long a = map.get("a");
        Long b = map.get("b");
        Long c = map.get("c");
        Long d = map.get("d");
        if ((a + b + c + d) == 0) {
            List<User> users = mapper.findUsersByDepartId(page, null, user.getReal_name());
            page.setRecords(users);
        } else {
            String departId = a > 0 ? "195" : (b > 0 ? "196" : (c > 0 ? "197" : "198"));
            System.out.println("departId = " + departId);
            List<User> users = mapper.findUsersByDepartId(page, departId, user.getReal_name());
            page.setRecords(users);
        }
        return page;
    }

    // 获取唯一的用户名，或编号
    public String getNumberByField(List<User> list, int count) {
        StringBuilder code = new StringBuilder();
        // 小于四位，前面补0
        if (count < 1000) {
            code.append("0" + count);
        }
        Optional<User> first = list.stream().filter(user -> code.toString().equals(user.getUser_code()) || code.toString().equals(user.getUser_name())).findFirst();
        if (first.isPresent()) {
            count++;
            return getNumberByField(list, count);
        } else {
            return code.toString();
        }
    }

    @Override
    public List<User> getUserByDepartsOrderByDepartIdAndUserId(String departs) {
        String[] arr = departs.split(",");
        List<User> list = mapper.getUserByDepartsOrderByDepartIdAndUserId(Arrays.asList(arr));
        return list;
    }

    @Override
    public User findBMFZRByDepartId(String depart_id) {
        QueryWrapper<DepartUser> departUserQuery = new QueryWrapper<>();
        departUserQuery.eq("depart_id", depart_id);
        List<DepartUser> departUserList = departUserService.list(departUserQuery);
        if (!(departUserList != null && departUserList.size() > 0)) {
            return null;
        }
        List<String> userIdList = departUserList.stream().map(departUser -> departUser.getUser_id()).collect(Collectors.toList());
        QueryWrapper<UserRole> userRoleQuery = new QueryWrapper<>();
        userRoleQuery.in("user_id", userIdList);
        List<UserRole> userRoleList = userRoleService.list(userRoleQuery);
        if (!(userRoleList != null && userRoleList.size() > 0)) {
            return null;
        }
        UserRole userRole = userRoleList.stream().filter(item -> "97".equals(item.getRole_id())).findFirst().orElse(null);//部门负责人
        if (userRole == null) {
            return null;
        }
        return this.getById(userRole.getUser_id());
    }

//    @Override
//    public void exportMenus(HttpServletResponse response, Map<String, Object> map) throws IOException {
//        ExportUser exportUser = JsonUtils.mapToObj((Map<String, Object>) map.get("params"), ExportUser.class);
//        long t1 = SystemClock.now();
//        List<ExportUser> menu = mapper.findAllUserMenu(exportUser);
//        List<ExportUser> role = mapper.findAllUserRole(exportUser);
//        List<ExportUser> list = Lists.newArrayList();
//        menu.forEach(m -> {
//            ExportUser eu = role.stream().filter(r -> r.getUser_id().equals(m.getUser_id())).findFirst().get();
//            m.setRole_id(eu.getRole_id());
//            m.setRole_name(eu.getRole_name());
//            list.add(m);
//        });
//        long t2 = SystemClock.now();
//        System.out.println("数据库查询：" + (t2 - t1));
//        exportData(response, list);
//    }

//    @Override
//    public void exportMenuDetails(HttpServletResponse response, Map<String, Object> map) throws IOException {
//        ExportUser exportUser = JsonUtils.mapToObj((Map<String, Object>) map.get("params"), ExportUser.class);
//        long t1 = SystemClock.now();
//        List<ExportUser> list = mapper.findAllUser(exportUser);
//        long t2 = SystemClock.now();
//        System.out.println("数据库查询：" + (t2 - t1));
//        exportData(response, list);
//    }

//    public void exportData(HttpServletResponse response, List<ExportUser> list) throws IOException {
//        List<ExportUser> results = Lists.newArrayList();
//        long t2 = SystemClock.now();
//        Set<String> userSet = new HashSet();
//        Set<String> userRoleSet = new HashSet();
//        List<ExportUser> first = list.stream().filter(it -> "0".equals(it.getParent_id()) && "菜单".equals(it.getLink_type())).collect(Collectors.toList());
//        List<ExportUser> menus = list.stream().filter(it -> "菜单".equals(it.getLink_type())).collect(Collectors.toList());
//        List<ExportUser> buttons = list.stream().filter(it -> "按钮".equals(it.getLink_type())).collect(Collectors.toList());
//        sub(menus, buttons, results, userSet, userRoleSet, first, 0);
//        long t3 = SystemClock.now();
//        System.out.println("数据处理：" + (t3 - t2));
//        export(response, results);
//        long t4 = SystemClock.now();
//        System.out.println("数据导出：" + (t4 - t3));
//    }

//    public void sub(List<ExportUser> menus, List<ExportUser> buttons, List<ExportUser> results, Set<String> userSet, Set<String> userRoleSet, List<ExportUser> sub, Integer level) {
//        level++;
//        for (ExportUser user : sub) {
//            String userId = user.getUser_id();
//            String userRoleId = user.getUser_id() + "_" + user.getRole_id();
//            boolean containsUser = userSet.contains(userId);
//            ExportUser result = new ExportUser();
//            if (containsUser) {// 不是第一个
//                result.setUser_name(null);
//                result.setReal_name(null);
//                result.setDepart_name(null);
//                result.setAll_depart_name(null);
//            } else {// 第一个
//                result.setUser_name(user.getUser_name());
//                result.setReal_name(user.getReal_name());
//                result.setDepart_name(user.getDepart_name());
//                result.setAll_depart_name(user.getAll_depart_name());
//            }
//            boolean containsUserRole = userRoleSet.contains(userRoleId);
//            if (containsUserRole) {// 不是第一个
//                result.setRole_name(null);
//            } else {// 第一个
//                result.setRole_name(user.getRole_name());
//            }
//            userSet.add(userId);
//            userRoleSet.add(userRoleId);
//            result.setResource_name(get(level, user.getLink_type()) + user.getResource_name());
//            result.setLink_type(user.getLink_type());
//            results.add(result);
//            /* ******************** 按钮处理 （start）********************** */
//            List<ExportUser> collect = buttons.stream().filter(it ->
//                    userId.equals(it.getUser_id()) &&
//                            user.getRole_id().equals(it.getRole_id()) &&
//                            user.getPermission_id().equals(it.getParent_id())
//            ).collect(Collectors.toList());
//            for (ExportUser button : collect) {
//                ExportUser resultButton = new ExportUser();
//                resultButton.setLink_type(button.getLink_type());
//                resultButton.setResource_name(get(level, button.getLink_type()) + button.getResource_name());
//                results.add(resultButton);
//            }
//            /* ******************** 按钮处理 （end）********************** */
//            List<ExportUser> child = menus.stream().filter(it ->
//                    userId.equals(it.getUser_id()) &&
//                            user.getRole_id().equals(it.getRole_id()) &&
//                            user.getPermission_id().equals(it.getParent_id())
//            ).collect(Collectors.toList());
//            sub(menus, buttons, results, userSet, userRoleSet, child, level);
//        }
//    }

    public static String get(Integer level, String type) {
        StringBuffer buffer = new StringBuffer();
        buffer.append("└");
        for (int i = 0; i < level; i++) {
            buffer.append("──");
        }
        if ("按钮".equals(type)) {
            buffer.append("──");
        }
        return buffer.toString();
    }

    // 大量数据导出
//    public void export(HttpServletResponse response, List<ExportUser> list) throws IOException {
//        response.setContentType("application/vnd.ms-excel");
//        response.setCharacterEncoding("utf-8");
//        //获取总数据量
//        Integer count = list.size();
//        int max = 5000;
//        int countTotal = count / max + 1;
//        //必须放到循环外，否则会刷新流
//        ExcelWriter excelWriter = EasyExcel.write(response.getOutputStream()).build();
//
//        /* *************************** 样式（start） *************************** */
////        WriteFont writeFont = new WriteFont();
////        writeFont.setFontName("Arial");
////        WriteCellStyle headStyle = new WriteCellStyle(); // 头的策略
////        headStyle.setFillForegroundColor(IndexedColors.RED.getIndex()); // 背景设置为红色
////        headStyle.setWriteFont(writeFont);
////        WriteCellStyle contentStyle = new WriteCellStyle();
////        contentStyle.setWriteFont(writeFont);
////        contentStyle.setWriteFont(writeFont);
////        // 这个策略是 头是头的样式 内容是内容的样式 其他的策略可以自己实现
////        HorizontalCellStyleStrategy horizontalCellStyleStrategy =
////                new HorizontalCellStyleStrategy(headStyle, contentStyle);
//        /* *************************** 样式（end） *************************** */
//
//        for (int i = 0; i < countTotal; i++) {
//            int start = i * max;
//            int end = countTotal == (i + 1) ? count : (i + 1) * max;
//            System.out.println("count:" + count + "  start:" + start + "  end:" + end);
//            List<ExportUser> data = list.subList(start, end);
//            WriteSheet writeSheet = EasyExcel.writerSheet(0, "用户信息").head(ExportUser.class)
//                    .registerWriteHandler(new LongestMatchColumnWidthStyleStrategy())
////                    .registerWriteHandler(horizontalCellStyleStrategy)//样式策略
//                    .build();
//            excelWriter.write(data, writeSheet);
//        }
//        //刷新流
//        excelWriter.finish();
//    }

    /**
     * 将base64编码字符串转换为图片
     */
    public String base64ToImage(String name, String base64) {
        try {
            String savePath = templateFileSavePath + "signature/";
            File file = new File(savePath);
            if (!file.exists()) {
                file.mkdirs();
            }
            String filename = name.concat("_").concat(DateTimeUtil.format(new Date(), DateTimeUtil.YEAR_TO_MILLION)).concat(".png");
            String imgPath = savePath.concat(filename);
            Base64.Decoder decoder = Base64.getDecoder(); // 解密
            base64 = base64.substring(base64.indexOf(",", 1) + 1, base64.length()); // 去掉base64前缀 data:image/jpeg;base64,
            byte[] b = decoder.decode(base64);
            // 处理数据
            for (int i = 0; i < b.length; ++i) {
                if (b[i] < 0) {
                    b[i] += 256;
                }
            }
            // System.out.println("图片保存位置："+imgPath);
            // 保存图片
            OutputStream out = new FileOutputStream(imgPath);
            out.write(b);
            out.flush();
            out.close();
            // 返回图片的相对路径 = 图片分类路径+图片名+图片后缀
            return "signature/" + filename;
        } catch (IOException e) {
            return null;
        }
    }

//    @Override
//    public List<User> findBySysDict(String code) {
//        Map<String, Object> map = new HashMap<>();
//        map.put("code", code);
//        Result dictInfo = sysClient.findSysDictInfo(map);
//        if (!dictInfo.isSuccess()) {
//            throw new BusinessRuntimeException(dictInfo.getMessage());//调用失败，抛出异常
//        }
//        List<Map<String, Object>> dictList = (List<Map<String, Object>>) dictInfo.getResult();
//        if (ArrayUtil.isEmpty(dictList)) {
//            throw new BusinessRuntimeException(code + "信息没有配置！");
//        }
//        Map<String, Object> dictMap = dictList.get(0);
//        String departs = (String) dictMap.get("value");
//
//        String[] arr = departs.split(",");
//        List<User> list = mapper.getUserByDepartsOrderByDepartIdAndUserId(Arrays.asList(arr));
//        return list;
//    }

    //查询所有子级的父ID
    public String allChildren(List<Depart> list, String ids, String id) {
        if (isNotChildren(list, id)) {
            for (Depart depart : list) {
                if (id.equals(depart.getPid())) {
                    ids = allChildren(list, ids, depart.getId());
                    ids += depart.getId() + ",";
                }
            }
            ids = ids + id + ",";
        } else{
            ids += id + ",";
        }
        return ids;
    }

    //判断是否还有子级
    public boolean isNotChildren(List<Depart> list, String id) {
        boolean boo = false;
        for (Depart depart : list) {
            if (id.equals(depart.getPid())) {
                boo = true;
                break;
            }
        }
        return boo;
    }

    @Override
    public JSONArray getRoleDetailsByUserId(String userId) {
        JSONArray arr = new JSONArray();
        List<Map<String, Object>> list = mapper.getRoleDetailsByUserId(userId);
        Set<String> roleIds = list.stream().map(it -> it.get("role_id") + "").collect(Collectors.toSet());
        if (roleIds.size() > 0) {
            for (String roleId : roleIds) {
                Optional<Map<String, Object>> roles = list.stream().filter(it -> roleId.equals(it.get("role_id") + "")).findFirst();
                if (roles.isPresent()) {
                    Map<String, Object> role = roles.get();
                    JSONObject obj = new JSONObject();
                    String level = "个人";
                    switch (role.get("data_authority_level") + "") {
                        case "0":
                            level = "个人";
                            break;
                        case "1":
                            level = "本部门";
                            break;
                        case "2":
                            level = "部门及以下部门";
                            break;
                        case "3":
                            level = "本企业";
                            break;
                        case "4":
                            level = "企业及以下企业";
                            break;
                        case "5":
                            level = "全部";
                            break;
                        case "6":
                            level = "自定义";
                            break;
                    }
                    String[] departIds = (role.get("role_depart") + "").split(",");
                    if (departIds.length > 0) {
                        QueryWrapper<Depart> queryWrapper = new QueryWrapper<>();
                        queryWrapper.eq("is_delete", "0");
                        queryWrapper.in("id", departIds);
                        List<Depart> departs = departService.list(queryWrapper);
                        List<String> collect = departs.stream().map(it -> it.getName()).collect(Collectors.toList());
                        obj.put("depart_name", collect.stream().collect(Collectors.joining(",")));
                    } else {
                        obj.put("depart_name", "");
                    }
                    obj.put("role_name", role.get("role_name"));
                    obj.put("data_authority_level", level);
                    obj.put("resource_name", "");
                    obj.put("link_type", "");// 0:菜单,1:按钮
                    obj.put("row-key", UUIDGenerator.getUUID());//唯一值，主要是elementUI需要用

                    // 菜单
                    List<Map<String, Object>> list1 = list.stream().filter(it -> (role.get("role_id") + "").equals(it.get("role_id") + "")
                            && "0".equals(it.get("link_type") + "")).collect(Collectors.toList());
                    menus(obj, list1, "0");
                    arr.add(obj);
                }
            }
        }
        return arr;
    }

//    @Override
//    public IPage<User> findOnlineUserPage(Page page, User user) {
//        Result result = wsClient.getOnlineUser();
//        if (!result.isSuccess()) {
//            throw new BusinessRuntimeException(result.getMessage());//调用失败，抛出异常
//        }
//        List<String> userSet = (List<String>) result.getResult();
//        user.setUserIds(userSet);
//        page.setRecords(mapper.findList(page, user));
//        return page;
//    }


    @Override
    public List<User> findChargeList(User user) {
        return mapper.getChargeList(user.getDepart_id());
    }

    @Override
    public List<User> getPersonsByGroups(User user) {
        String name = "";
        switch (user.getDepart_id()){
            case "195":
                name="项目联系函_第一研究院生产副院长";
                break;
            case "196":
                name="项目联系函_第二研究院生产副院长";
                break;
            case "197":
                name="项目联系函_第三研究院生产副院长";
                break;
            case "198":
                name="项目联系函_第四研究院生产副院长";
                break;
            case "224":
                name="项目联系函_材料与结构综合研究院副院长";
                break;
            case "225":
                name="项目联系函_建筑节能与幕墙研究院副院长";
                break;
            case "226":
                name="项目联系函_道路桥梁研究院副院长";
                break;
            case "227":
                name="项目联系函_测绘与岩土工程研究院副院长";
                break;
            case "228":
                name="项目联系函_钢结构与特种设备研究院副院长";
                break;
            case "229":
                name="项目联系函_司法鉴定研究院副院长";
                break;
            case "230":
                name="项目联系函_绿色低碳产业创新研究院副院长";
                break;
            case "256":
                name="项目联系函_建筑材料研究院副院长";
                break;
            case "286":
                name="项目联系函_建筑幕墙研究院副院长";
                break;
            case "291":
                name="项目联系函_建筑节能研究院副院长";
                break;
            case "299":
                name="项目联系函_建筑结构研究院副院长";
                break;
            case "298":
                name="项目联系函_安全应急研究院副院长";
                break;
            case "303":
                name="项目联系函_材料节能幕墙研究院副院长";
                break;
            case "304":
                name="项目联系函_市政桥梁与测绘岩土研究院副院长";
                break;
            case "308":
                name="项目联系函_工程监理科研院副院长";
                break;
            case "309":
                name="项目联系函_工程咨询科研院副院长";
                break;
        }
        Map<String,Object> map =  mapper.findGroupList(name);
        List<User> users = new ArrayList<>();
        if(map.get("groups")!=null){
            List<String> list = Arrays.asList(String.valueOf(map.get("groups")).split(","));
            User user1 = new User();
            user1.setUserIds(list);
            users = mapper.findList(user1);
        }
        return users;
    }

    void menus(JSONObject obj, List<Map<String, Object>> list, String pid) {
        List<Map<String, Object>> firsts = list.stream().filter(it -> pid.equals(it.get("parent_id") + "")).collect(Collectors.toList());
        if (firsts.size() > 0) {
            JSONArray arr1 = new JSONArray();
            for (Map<String, Object> firstMap : firsts) {
                JSONObject obj1 = new JSONObject();
                String resource_name = firstMap.get("resource_name") + "";
                String parent_id = firstMap.get("id") + "";
                // String link_type = firstMap.get("link_type") + "";

                obj1.put("role_name", "");
                obj1.put("data_authority_level", "");
                obj1.put("depart_name", "");
                obj1.put("resource_name", resource_name);
                // obj1.put("link_type", ("0".equals(link_type) ? "菜单" : "按钮"));// 0:菜单,1:按钮
                obj1.put("row-key", UUIDGenerator.getUUID());//唯一值，主要是elementUI需要用

                menus(obj1, list, parent_id);
                arr1.add(obj1);
            }
            obj.put("children", arr1);
        }
    }

    @Override
    public List<User> getStatisticUser(User user) {
        List<User> tempUserList = new ArrayList<>();
        List<User> userList = new ArrayList<>();
        List<String> departIdList = new ArrayList<>();
        
        //首先把本部门加进去
        departIdList.add(user.getDepart_id());
        //获取该部门的子部门
        getSubDepartRecursion(user.getDepart_id(), departIdList);
        
        //获取所有人员
        User u = new User();
        u.setIs_delete("0");
        List<User> allUserList = mapper.findList(u);

        getUser(user.getDepart_id(), departIdList, allUserList, tempUserList);

        //根据人员中的Is_project_contract_statistic把人员分为主要统计人员和”其他“
        for(User u1: tempUserList){
            if("1".equals(u1.getIs_project_contract_statistic())){
                userList.add(u1);
            }
        }
        //如果部门中人员数量大于需要统计的人员，则添加”其他“代表其他人员
        if(tempUserList.size() > userList.size()){
            User other = new User();
            //该id在合同统计中需要用到，用来区分“其他人员”和统计对象
            other.setId("other");
            other.setReal_name("其他");
            userList.add(other);
        }
        return userList;
    }

    @Override
    public List<User> getJiuzhouStatisticUser(User user) {
        List<User> tempUserList = new ArrayList<>();
        List<User> userList = new ArrayList<>();
        List<String> departIdList = new ArrayList<>();

        //首先把本部门加进去
        departIdList.add(user.getDepart_id());
        //获取该部门的子部门
        getSubDepartRecursion(user.getDepart_id(), departIdList);

        //获取所有人员
        User u = new User();
        u.setIs_delete("0");
        List<User> allUserList = mapper.findList(u);

        getUser(user.getDepart_id(), departIdList, allUserList, tempUserList);

        //根据人员中的Is_project_contract_statistic把人员分为主要统计人员和”其他“
        for(User u1: tempUserList){
            if("1".equals(u1.getIs_project_contract_statistic())){
                userList.add(u1);
            }
        }
        return userList;
    }

//    @Override
//    public List<User> getJiuzhouByRoleId() {
//        return mapper.findJiuzhouByRoleId();
//    }

    @Override
    public List<Role> findRolesByUserId(String user_id) {
        return mapper.findRolesByUserId(user_id);
    }

    //根据部门id，找到该部门下的所有子部门
    private void getSubDepartRecursion(String departId, List<String> list){
        QueryWrapper<Depart> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("pid", departId);
        queryWrapper.eq("is_delete", "0");
        List<Depart> tempList = departService.list(queryWrapper);

        if(CollUtil.isEmpty(tempList)){
            return;
        }
        for(Depart depart: tempList){
            list.add(depart.getId());
            getSubDepartRecursion(depart.getId(), list);
        }
    }

    //根据部门id，找到部门下的所有人员（去重,内部人员）
    private void getUser(String topDepartId, List<String> departIdList, List<User> allUserList, List<User> userList){
        DepartUser du = new DepartUser();
        du.setDepartIdList(departIdList);

        QueryWrapper<DepartUser> queryWrapper = new QueryWrapper<>();
        if (du.getDepartIdList() != null && du.getDepartIdList().size() > 0) {
            queryWrapper.in("depart_id", du.getDepartIdList());
        }

        List<DepartUser> tempList = departUserService.list(queryWrapper);

        if(CollUtil.isEmpty(tempList)){
            return;
        }

        for(DepartUser departUser: tempList){
            //判断userList中是否包含这个用户的id
            boolean contains = userList.stream().anyMatch(user -> user.getId().equals(departUser.getUser_id()));
            if(!contains){
                User user = new User();
                user.setId(departUser.getUser_id());
                userList.add(user);
            }
        }
        for(User user: allUserList){
            for(User u: userList){
                //is_outer表示内部人员
                if(user.getId().equals(u.getId()) && "0".equals(user.getIs_outer())){
                    //这里临时把用户设置到顶级部门
                    u.setMain_dept(topDepartId);
                    u.setIs_project_contract_statistic(user.getIs_project_contract_statistic());
                    u.setReal_name(user.getReal_name());
                    u.setIs_outer(user.getIs_outer());
                }
            }
        }
    }

//    @Override
//    public List<User> getDirectorByDepartId(String departId, String positionCode) {
//        // String DirectorPositionCode = "P201";
//        //根据岗位id查找院长信息
//        QueryWrapper<Position> queryWrapper = new QueryWrapper<>();
//        // queryWrapper.eq("code", DirectorPositionCode);
//        queryWrapper.eq("code", positionCode);
//        queryWrapper.eq("is_delete", "0");
//        Position position = positionService.getOne(queryWrapper);
//        return mapper.getDirectorByDepartId(departId, position.getId());
//    }

    @Override
    public List<User> findUserByRealName(User user) {
        return mapper.findUserByRealName(user);
    }

}
